import { } from '@mantine/core'
import { get, has } from 'lodash-es'
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, CreateAxiosDefaults, InternalAxiosRequestConfig } from "axios";
import { BaseResponse } from './model';


class Request {

  instance: AxiosInstance;
  axiosConfigs?: CreateAxiosDefaults = {
    baseURL: 'http://localhost:5173',
    timeout: 20000
  };

  constructor() {
    this.instance = axios.create(this.axiosConfigs);
    this.instance.interceptors.request.use(
      this.requestSuccHandler.bind(this),
      this.requestFailedHandler.bind(this)
    );
    this.instance.interceptors.response.use(
      this.responseSuccHandler.bind(this),
      this.responseFailedHandler.bind(this)
    )
  }

  get(url: string, params?: AxiosRequestConfig<any>) {
    return this.instance.get(url, params)
  }

  post<T>(url: string, data?: any, params?: AxiosRequestConfig<any>) {
    return this.instance.post<any, BaseResponse<T>>(url, data, params)
  }

  put(url: string, data?: any, params?: AxiosRequestConfig<any>) {
    return this.instance.put(url, data, params)
  }

  delete(url: string, params?: AxiosRequestConfig<any>) {
    return this.instance.delete(url, params)
  }

  /** 请求拦截器 */
  requestSuccHandler(config: InternalAxiosRequestConfig<any>) {
    console.log('请求拦截器：', config);
    return config
  }

  /** 请求错误拦截器 */
  requestFailedHandler(err: any) {
    return Promise.reject(err)
  }
  
  /** 响应拦截器 */
  responseSuccHandler(resp: AxiosResponse<any, any>) {
    
    if (has(resp, 'data.code')) {
      const code = get(resp, 'data.code');
      if (code !== 200) {

      }

      return resp.data
    }
    
    return resp
  }

  /** 响应错误拦截器 */
  responseFailedHandler(err: any) {
    return Promise.reject(err)
  }
}


export default new Request()